<template>
  <div class="home-container">
    <el-container>
      <el-header class="el-header">
        <el-text tag="b" size="large" class="header-title">
          {{ currentMenu === '2' ? '餐厅' : '首页' }}
        </el-text>

        <div style="display: flex; align-items: center;">
          <el-tooltip
              effect="light"
              content="Gitee仓库"
              placement="bottom">
            <el-button style="margin-right: 30px" :icon="Reading" circle></el-button>
          </el-tooltip>

          <!-- 头像 -->
          <el-dropdown>
            <el-avatar style="margin-right: 20px" :size="35" :icon="Avatar"></el-avatar>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :icon="UserFilled" @click="goToUserProfile">个人中心</el-dropdown-item>
                <el-dropdown-item :icon="StarFilled">收藏</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-container>
        <el-aside class="el-aside">
          <el-menu :default-active="currentMenu" @select="handleMenuSelect">
            <el-menu-item index="1">
              <el-icon>
                <House/>
              </el-icon>
              <span>首页</span>
            </el-menu-item>
            <el-menu-item index="2">
              <el-icon>
                <Shop/>
              </el-icon>
              <span>餐厅</span>
            </el-menu-item>
            <el-menu-item index="3" @click="AboutDialog = true">
              <el-icon>
                <InfoFilled/>
              </el-icon>
              <span>关于</span>
            </el-menu-item>
          </el-menu>
        </el-aside>

        <el-main class="main-content">
          <!-- 首页部分，只显示评分 >= 4.3 的餐厅 -->
          <div v-if="currentMenu === '1'">
            <div>
              <el-text truncated class="welcome-text">
                欢迎使用惊喜一餐!
              </el-text>
            </div>
            <h3 style="color: #434343">推荐餐厅</h3>
            <el-button type="primary" @click="openSurpriseDrawer" style="margin-bottom: 20px">惊喜一餐</el-button>
            <el-empty v-if="filteredRestaurants.length < 1" description="暂无餐厅信息"/>
            <el-row :gutter="20">
              <el-col :span="8" v-for="restaurant in filteredRestaurants" :key="restaurant.id">
                <el-card @click="goToRestaurantDetail(restaurant)">
                  <img :src="restaurant.image" class="restaurant-image" alt="餐厅图片"/>
                  <div style="padding: 14px;">
                    <span>
                      {{ restaurant.name }}
                      <el-tag
                          v-if="restaurant.rating >= 4.3"
                          type="success"
                          effect="light"
                          round
                      >
                        好评如潮
                      </el-tag>
                      <el-tag
                          v-else-if="restaurant.rating > 2.5"
                          type="warning"
                          effect="light"
                          round
                      >
                        褒贬不一
                      </el-tag>
                      <el-tag v-else type="danger" effect="light" round>差评如潮</el-tag>
                    </span>
                    <p>{{ restaurant.address }}</p>
                    <el-rate
                        v-model="restaurant.rating"
                        disabled
                        show-score
                        score-template="{value} 分"
                    />
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 餐厅部分，显示所有餐厅 -->
          <div v-else-if="currentMenu === '2'">
            <h3 style="color: #434343">所有餐厅</h3>
            <!-- 添加餐厅表单 -->
            <el-form @submit.native.prevent="addRestaurant" inline>
              <el-form-item label="名称">
                <el-input v-model="newRestaurant.name" placeholder="请输入餐厅名称"></el-input>
              </el-form-item>
              <el-form-item label="地址">
                <el-input v-model="newRestaurant.address" placeholder="请输入餐厅地址"></el-input>
              </el-form-item>
              <el-form-item label="评分">
                <el-rate v-model="newRestaurant.rating" show-score></el-rate>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="addRestaurant">添加餐厅</el-button>
              </el-form-item>
            </el-form>

            <!-- 删除餐厅表单 -->
            <el-form @submit.native.prevent="deleteRestaurant" inline>
              <el-form-item label="删除餐厅ID">
                <el-input v-model="deleteRestaurantId" placeholder="请输入餐厅ID"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="danger" @click="deleteRestaurant">删除餐厅</el-button>
              </el-form-item>
            </el-form>

            <el-empty v-if="restaurants.length < 1" description="暂无餐厅信息"/>
            <el-row :gutter="20">
              <el-col :span="8" v-for="restaurant in restaurants" :key="restaurant.id">
                <el-card @click="goToRestaurantDetail(restaurant)">
                  <img :src="restaurant.image" class="restaurant-image" alt="餐厅图片"/>
                  <div style="padding: 14px;">
                    <span>
                      {{ restaurant.name }}
                      <el-tag
                          v-if="restaurant.rating >= 4.3"
                          type="success"
                          effect="light"
                          round
                      >
                        好评如潮
                      </el-tag>
                      <el-tag
                          v-else-if="restaurant.rating > 2.5"
                          type="warning"
                          effect="light"
                          round
                      >
                        褒贬不一
                      </el-tag>
                      <el-tag v-else type="danger" effect="light" round>差评如潮</el-tag>
                    </span>
                    <p>{{ restaurant.address }}</p>
                    <el-rate
                        v-model="restaurant.rating"
                        disabled
                        show-score
                        score-template="{value} 分"
                    />
                    <!-- 编辑按钮 -->
                    <el-button size="small" type="primary" @click.stop="openEditDialog(restaurant)">编辑</el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 编辑餐厅的对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑餐厅" width="500" center>
      <el-form :model="editRestaurant" ref="editForm">
        <el-form-item label="名称">
          <el-input v-model="editRestaurant.name" placeholder="请输入餐厅名称"/>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="editRestaurant.address" placeholder="请输入餐厅地址"/>
        </el-form-item>
        <el-form-item label="评分">
          <el-input
              v-model="editRestaurant.rating"
              placeholder="请输入评分 (0-5)"
              @blur="validateRating"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateRestaurant">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 抽屉 -->
    <el-drawer
        title="惊喜推荐"
        v-model="surpriseDrawerVisible"
        direction="rtl"
        size="40%"
    >
      <el-form @submit.native.prevent="getRecommendMeal">
        <el-form-item label="输入您的需求">
          <el-input type="textarea" v-model="userInput" placeholder="请输入您的需求"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getRecommendMeal">推荐</el-button>
        </el-form-item>
      </el-form>
      <div v-if="recommendMeals.length > 0">
        <el-row :gutter="20">
          <el-col :span="24" v-for="(meal, index) in recommendMeals" :key="index">
            <el-card>
              <div>{{ meal }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-drawer>

    <!-- 关于的对话框 -->
    <el-dialog v-model="AboutDialog" title="作者信息" width="500" center>
      <span>
        学号：22111303093；姓名：吴雨森
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="AboutDialog = false">OK</el-button>
        </div>
      </template>
    </el-dialog>

    <el-backtop/>
  </div>
</template>


<script>

import {defineComponent} from "vue";
import {Avatar, House, InfoFilled, Reading, Shop, StarFilled, UserFilled} from "@element-plus/icons-vue";
import axios from "axios"; // 引入 useRouter

export default defineComponent({
  computed: {
    StarFilled() {
      return StarFilled
    },
    UserFilled() {
      return UserFilled
    },
    Avatar() {
      return Avatar
    },
    Reading() {
      return Reading
    },
    // 只显示评分 >= 4.3 的餐厅
    filteredRestaurants() {
      return this.restaurants.filter(restaurant => restaurant.rating >= 4.3);
    }
  },
  data() {
    return {
      currentMenu: "1", // 当前激活的菜单项，'1' 为首页，'2' 为餐厅
      restaurants: [],
      AboutDialog: false,
      newRestaurant: {name: '', address: '', rating: 0}, // 新增餐厅表单数据
      deleteRestaurantId: '', // 删除餐厅ID
      editDialogVisible: false,
      editRestaurant: {id: '', name: '', address: '', rating: 0},
      surpriseDrawerVisible: false,
      userInput: '',
      recommendMeals: [],
    }
  },
  mounted() {
    this.fetchRestaurants();
  },
  methods: {
    // 跳转到个人中心页面
    goToUserProfile() {
      this.$router.push({name: 'UserProfile'}); // 跳转到UserProfile.vue
    },
    // 处理菜单选择
    handleMenuSelect(index) {
      this.currentMenu = index;
    },
    goToRestaurantDetail(restaurant) {
      this.$router.push({
        name: 'RestaurantDetail',
        params: {name: restaurant.name},
        query: {
          image: restaurant.image,
          address: restaurant.address,
          rating: restaurant.rating,
        }
      });
    },
    fetchRestaurants() {
      axios.get('/restaurants/all')
          .then(response => {
            this.restaurants = response.data.data;
            console.log(response.data);
            console.log(response.data.data);
          })
          .catch(error => {
            console.error('获取餐馆时出错：', error);
          });
    },
    addRestaurant() {
      axios.post('/restaurants/add', this.newRestaurant)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('添加餐厅成功');
              this.fetchRestaurants(); // 重新获取餐厅数据
              this.newRestaurant = {name: '', address: '', rating: 0}; // 重置表单
            } else {
              this.$message.error('添加餐厅失败');
            }
          })
          .catch(error => {
            console.error('添加餐厅时出错：', error);
            this.$message.error('添加餐厅时网络错误');
          });
    },
    deleteRestaurant() {
      axios.delete(`/restaurants/delete/${this.deleteRestaurantId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除餐厅成功');
              this.fetchRestaurants(); // 重新获取餐厅数据
              this.deleteRestaurantId = ''; // 重置删除ID
            } else {
              this.$message.error('删除餐厅失败');
            }
          })
          .catch(error => {
            console.error('删除餐厅时出错：', error);
            this.$message.error('删除餐厅时网络错误');
          });
    },
    openEditDialog(restaurant) {
      this.editRestaurant = {...restaurant};  // 复制餐厅数据到编辑表单
      this.editDialogVisible = true;
    },
    updateRestaurant() {
      axios.put(`/restaurants/update`, this.editRestaurant)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('更新餐厅成功');
              this.fetchRestaurants();  // 重新获取餐厅数据
              this.editDialogVisible = false;
            } else {
              this.$message.error('更新餐厅失败');
            }
          })
          .catch(error => {
            console.error('更新餐厅时出错：', error);
            console.log(this.editRestaurant);  // 打印查看传递的数据
            this.$message.error('更新餐厅时网络错误');
          });
    },
    validateRating() {
      const rating = parseFloat(this.editRestaurant.rating);
      if (isNaN(rating) || rating < 0) {
        this.editRestaurant.rating = 0.0;
      } else if (rating > 5) {
        this.editRestaurant.rating = 5.0;
      } else {
        this.editRestaurant.rating = parseFloat(rating.toFixed(1));
      }
    },
    openSurpriseDrawer() {
      this.surpriseDrawerVisible = true;
    },
    getRecommendMeal() {
      axios.post('/api/recommendMeal', {
        prompt: this.userInput,
      })
          .then(response => {
            console.log('Response.data:', response.data);  // 打印完整响应
            this.recommendMeals.unshift(response.data); // 将新推荐信息添加到数组的开头
          })
          .catch(error => {
            console.error('获取推荐时出错：', error);
            this.$message.error('获取推荐失败');
          });
    },
  },
  components: {Shop, Avatar, InfoFilled, House}
})
</script>

<style scoped>
.home-container {
  text-align: center;
  background-color: #f2f3f5;
}

.el-header {
  background-color: rgb(230, 232, 235);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  margin-left: 1%;
  letter-spacing: 20px;
  font-size: 24px;
}

.el-aside {
  width: 15%;
}

.el-aside span {
  margin-left: 4%;
  font-size: 18px;
  letter-spacing: 8px;
}

.el-menu-item {
  background: #f2f3f5;
  border: 0;
}

.el-menu-item:hover {
  background: #ffffff;
}

.el-menu-item.is-active {
  background: #f8f8f8;
  font-weight: bold;
}

.main-content {
  padding: 20px;
}

.welcome-text {
  font-size: 40px;
}

.restaurant-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  margin-bottom: 20px;
}

.el-card:hover {
  transform: translateY(-5px); /* 向上移动5px */
  transition: transform 0.3s ease-in-out; /* 动画持续时间0.3秒 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}

.el-dialog .el-form-item {
  margin-bottom: 20px;
}

.el-drawer__title {
  font-weight: bold;
}

</style>